package tech.veedo.munchkin.controllers.backend;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import tech.veedo.munchkin.beans.basic.User;
import tech.veedo.munchkin.beans.backend.Mapping;
import tech.veedo.munchkin.constants.Operation;
import tech.veedo.munchkin.services.backend.MappingService;
import tech.veedo.munchkin.verifications.backend.MappingVerify;

import java.util.HashMap;

@Slf4j
@RestController
@Api(tags = "1-后台-2-实体工作流接口集合")
@RequestMapping("/munc/mapping")
public class MappingController {

    private final MappingService mappingService;

    private final MappingVerify mappingVerify;

    public MappingController(MappingService mappingService, MappingVerify mappingVerify) {
        this.mappingService = mappingService;
        this.mappingVerify = mappingVerify;
    }

    @ApiOperation("保存实体工作流接口")
    @PostMapping("/save")
    public boolean save(@RequestBody Mapping mapping) {
        mappingVerify.verify(Operation.ADD, mapping);
        return mappingService.saveMapping(mapping, User.defaultU());
    }

    @ApiOperation(("更新实体工作流接口"))
    @PostMapping("/update")
    public boolean update(@RequestBody Mapping mapping) {
        mappingVerify.verify(Operation.UPDATE, mapping);
        return mappingService.updateMapping(mapping, User.defaultU());
    }

    @ApiOperation("根据顶层工作流id和所属机构编码获取实体工作流分页列表")
    @PostMapping("/page")
    public Page<Mapping> page(@RequestBody HashMap<String, Object> params) {
        if (!params.containsKey("workflowID") || ObjectUtils.isEmpty(params.get("workflowID"))) {
            throw new NullPointerException("缺失顶层工作流id参数或参数为空");
        }
        if (!params.containsKey("orgCode") || ObjectUtils.isEmpty(params.get("orgCode"))) {
            throw new NullPointerException("缺失机构编码参数或参数为空");
        }
        return mappingService.pageMapping(params);
    }

    @ApiOperation("删除实体工作流")
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Long id) {
        if (ObjectUtils.isEmpty(id)) {
            throw new NullPointerException("要删除的实体工作流id为空");
        }
        return mappingService.deleteMapping(id);
    }

    @ApiOperation("启用实体工作流")
    @GetMapping("/start/{id}")
    public boolean start(@PathVariable Long id) {
        if (ObjectUtils.isEmpty(id)) {
            throw new NullPointerException("要启用的实体工作流id为空");
        }
        return mappingService.start(id);
    }

    @ApiOperation("停用实体工作流")
    @GetMapping("/stop/{id}")
    public boolean stop(@PathVariable Long id) {
        if (ObjectUtils.isEmpty(id)) {
            throw new NullPointerException("要停用的实体工作流id为空");
        }
        return mappingService.stop(id);
    }

}
